<template>
<div>
  <my-form :model="model" @submit="handleSubmit" :footer="true">
    <my-cascader name="value" label="多选" :options="tree" v-model="model.value"
      :props="{ props: {multiple: true}, clearable: true, showAllLevels: false }"
    >
    </my-cascader>
  </my-form>
  <ul>
    <li v-for="(item, index) in showLabel(ids)" :key="index">{{item}}</li>
  </ul>
  <div>
    <el-button size="mini" @click="sendBack">回填</el-button>

    <el-button size="mini" @click="ruffle">乱序</el-button>
  </div>

</div>
</template>
<style lang="scss" scope>
</style>
<script> 
import tree from '../assets/tree.json'
export default {
  components: {},
  data() {
    return {
      tree: tree,
      model: {
        value: []
      },
      ids: []
    }
  },
  computed: {},
  methods: {
    handleSubmit(model) {
      this.ids = this.model.value.reduce((total, arr) => {
        total.push(arr[arr.length - 1])
        return total
      }, []) 
    },
    findLevel(opts, id, arr) {
      for (let index = 0; index < opts.length; index++) {
        if (opts[index].id === id) {
          arr.unshift(opts[index].id) 
          if (opts[index].parentId) {
            this.findLevel(opts, opts[index].parentId, arr)
          }
        }
      }
    },
    showLabel(ids) {
      return ids.map((id) => {
        return this.tree.find((item) => {
          return item.id === id
        }).label
      })
    },
    sendBack() {
      this.model.value = this.ids.reduce((total, id) => {
        const arr = []
        this.findLevel(this.tree, id, arr)
        if (arr.length) {
          total.push(arr)
        }
        return total
      }, [])
    },
    ruffle() {
      this.ids = this._sort(this.ids)
    },
    _sort(arr) {
      let newArr = []
      newArr = arr.sort(() => { return Math.random() - 0.5 })
      return newArr
    }
  },
  created() {},
  mounted() {
    console.log(this.tree)
  }
}
</script>
